import './assets/tailwind.css'
import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import App from './App.vue'
import router from './router'
import { useAuthStore } from '@/stores/auth'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

// Register all Element Plus icons globally
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// Setup navigation guard
router.beforeEach(async (to) => {
  const authStore = useAuthStore()
  
  // Check auth state on initial load
  if (!authStore.isAuthenticated && authStore.token) {
    await authStore.checkAuth()
  }

  // Redirect logged-in users away from guest-only pages
  if (to.meta.guestOnly && authStore.isAuthenticated) {
    return authStore.isAdmin ? '/admin/dashboard' :
           authStore.isEmployee ? '/employee/dashboard' : 
           '/customer/dashboard'
  }

  // Check auth for protected routes
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return '/login'
  }

  // Check role permissions
  if (to.meta.allowedRoles && !to.meta.allowedRoles.includes(authStore.userRole())) {
    return authStore.isAdmin ? '/admin/dashboard' :
           authStore.isEmployee ? '/employee/dashboard' : 
           '/customer/dashboard'
  }
})

app.mount('#app')
